﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NATAR.Presentation
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate("s2.travian.us");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlDocument document = webBrowser1.Document;
            if (document != null)
            {
                loginButton.Enabled = document.Url.OriginalString == "http://s2.travian.us/";
            }
        }

        private void loginButton_Click(object sender, EventArgs e)
        {
            HtmlDocument document = webBrowser1.Document;
            if (document == null)
            {
                throw new InvalidOperationException("The web browser does not have an HTML document loaded.");
            }

            if (document.Url.OriginalString != "http://s2.travian.us/")
            {
                return;
            }

            if (document.Forms.Count != 1)
            {
                throw new InvalidOperationException("The HTML document has more forms than expected during login.");
            }
            HtmlElement loginForm = document.Forms[0];

            HtmlElement loginTable = document.GetElementById("login_form");
            if (loginTable == null)
            {
                throw new InvalidOperationException("Could not find the login table.");
            }

            HtmlElementCollection inputs = loginTable.GetElementsByTagName("input");
            if (inputs == null || inputs.Count == 0)
            {
                throw new InvalidOperationException("Could not find the username or password text boxes.");
            }
            if (inputs.Count > 2)
            {
                throw new InvalidOperationException("The number of text boxes in the login form is greater than expected.");
            }
            inputs[0].InnerText = name.Text;
            inputs[1].InnerText = password.Text;

            loginForm.InvokeMember("submit");
        }
    }
}
